/*
  Copyright (C) 2013 Napspirit / Thierry Rochelet

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.
  
  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
  
  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package com.napspirit.tmx.ui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ComboBoxPopup 
    implements ActionListener {

    private JComboBox comboListBox;
    private JDialog dialog;
    private JButton cancelButton;

    public ComboBoxPopup() {
    }

    public int close() {
        this.dialog.setVisible(false);
        this.dialog.dispose();        
        this.dialog = null;

        return comboListBox.getSelectedIndex();
    }

    public void open(JButton actionButton, Object[] comboItems, String actionString, JFrame parent) {
        
        if (this.dialog == null && comboItems.length > 0) {
            this.dialog = new JDialog(parent, actionString);

            // Make sure this can be killed with the [X] button
            this.dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);

            this.dialog.setLocationRelativeTo(parent);
            this.dialog.setResizable(false);

            comboListBox = new JComboBox(comboItems);

            JPanel popupPanel = new JPanel();

            popupPanel.add(comboListBox);
            popupPanel.add(actionButton);

            this.cancelButton = new JButton("Cancel");
            this.cancelButton.addActionListener(this);

            popupPanel.add(this.cancelButton);

            this.dialog.getContentPane().add(popupPanel);
            this.dialog.pack();
            this.dialog.setVisible(true);
        }

    }

    /**
     * Action handling method for cancel button
     */
    public void actionPerformed(ActionEvent e) {

        if (e.getSource() == this.cancelButton) {
            this.dialog.setVisible(false);
            this.dialog.dispose();
            this.dialog = null;
        }
    }
}
